package com.hns.frame.security;

import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.hns.can.base.entity.SysRoleEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.base.service.SysRoleService;
import com.hns.can.base.service.SysUserService;
import com.hns.frame.enumrate.EnabledSt;

/**
 * 登录服务
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class AppUserDetailsService implements UserDetailsService {
    @Autowired
    private SysRoleService    sysRoleService;
    
    @Autowired
    private SysUserService sysUserService;
    
    /**
     * 登录用户校验 和 载入登陆者信息
     * @param 用户名
     * @return  用户信息
     * @throws UsernameNotFoundException
     * @throws DataAccessException
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        SysUserEntity entity = new SysUserEntity();
//        String[] loginInfo = userName.split("#type#");
//        String loginType = "";
//        if(loginInfo.length > 1){
//            loginType = loginInfo[1];
//            entity.setAcctName(loginInfo[0]);
//            entity.setLoginType(loginType);
//        }else{
//            entity.setAcctName(userName);
//        }
        entity.setAcctName(userName);
        entity.setIsClosed(EnabledSt.DISABLE.getFlag());
        final List<SysUserEntity> userList = sysUserService.getSysUserListByName(entity);
        if (userList != null && userList.size() > 0) {
            entity = userList.get(0);
            //entity.setLoginType(loginType);
        } else {
            return null;
        }
        
        //根据id获取对应的角色
        List<SysRoleEntity> sysRoleList = sysRoleService.getSysRoleListByUserId(entity.getId());
        return new AppUserDetailsImpl(entity, new HashSet<SysRoleEntity>(sysRoleList));
    }
    
}
